package com.crb.oauth2.api.wechat.cp.controller;

import com.crb.oauth2.api.wechat.cp.config.WxCpConfiguration;
import com.crb.oauth2.api.wechat.cp.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.util.UUID;


/**
 * 扫码登录
 * OAuth2.0
 *
 * @author huangjian
 */
@Slf4j
@Controller
@RequestMapping("/wx/cp/oauth_qr/{agentId}")
public class WxQrOauthController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/oauth2")
    public String oauth2(@PathVariable Integer agentId,ModelMap map) {
        String url = super.getServerDomain()+"/wx/cp/oauth_qr/" + agentId + "/greet";
        String redirect_uri = "";
        try {
            redirect_uri = java.net.URLEncoder.encode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("ecdoe error: " + e.getMessage());
        }
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        map.put("appid", cpService.getWxCpConfigStorage().getCorpId());
        map.put("redirect_uri", redirect_uri);
        map.put("agentid", agentId);
        map.put("state", UUID.randomUUID().toString());
        return "oauth2_qr";
    }

    @RequestMapping("/greet")
    public String greetUser(@PathVariable Integer agentId, @RequestParam String code, ModelMap map) {
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        if (cpService==null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%s]的配置，请核实！", agentId));
        }
        try {
            WxCpOauth2UserInfo userInfo = cpService.getOauth2Service().getUserInfo(code);
            String openId = userInfo.getOpenId();
            String userId = userInfo.getUserId();
            WxCpUserService userService = cpService.getUserService();
            //兼容企业微信和微信两种认证方式
            if(!StringUtils.isNotEmpty(userId)) {
                userId = userService.openid2UserId(openId);
            }
            WxCpUser user = userService.getById(userId);
            map.put("user", user);
            log.info(JsonUtils.toJson(user));
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "greet_user";
    }
}
